.export _roll

width = 13
voffset = 40
lookfor = 32

.data
charmap:  .word ($0400)
colormap: .word ($d800)

.code
_roll:
	; Save ZP
	lda $ff
	pha
	lda $fe
	pha
	lda $fd
	pha
	lda $fc
	pha

	lda charmap + 1
	sta $ff
	lda charmap
	sta $fe

	lda colormap + 1
	sta $fd
	lda colormap
	sta $fc

	; clear first 10 bytes of buffer
	ldx #width
	ldy #$00
ab:	lda #lookfor
	sta ($fe),y
	iny
	dex
	bne ab

roll_search:
	ldy #voffset
	lda ($fe), y
	cmp #lookfor
	bne roll_found
	
	lda $fe
	clc
	adc #(voffset)
	bcc roll_continue_1
	inc $ff
roll_continue_1:
	sta $fe

	lda $fc
	clc
	adc #(voffset)
	bcc roll_continue_2
	inc $fd
roll_continue_2:
	sta $fc
	jmp roll_jump 

roll_increment:
	lda $fe
	clc
	adc #(voffset - width)
	bcc roll_continue_found_1
	inc $ff
roll_continue_found_1:
	sta $fe

	lda $fc
	clc
	adc #(voffset - width)
	bcc roll_continue_found_2
	inc $fd
roll_continue_found_2:
	sta $fc

roll_jump:
	lda $fe
	cmp #<($0400 + 920)
	bne roll_search
	lda $ff
	cmp #>($0400 + 920)
	bne roll_search
	jmp roll_done

roll_found:
	ldx #width
roll_loop:
	ldy #voffset
	lda ($fe),y
	ldy #$00
	sta ($fe),y
	ldy #voffset
	lda ($fc),y
	ldy #$00
	sta ($fc),y
	ldy #voffset
	lda #lookfor
	sta ($fe),y
	inc $fe
	bne roll_loop_cont1
	inc $ff
roll_loop_cont1:
	inc $fc
	bne roll_loop_cont2
	inc $fd
roll_loop_cont2:
	dex
	bne roll_loop
	jmp roll_increment

roll_done:
	; Restore ZP
	pla 
	sta $fc
	pla
	sta $fd
	pla 
	sta $fe
	pla
	sta $ff
	rts